package velha;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.*;

import velha.connection.bt.BTMenu;
import velha.connection.net.NETMenu;
import velha.game.Constantes;
import velha.game.Player;
import velha.game.Rival;
import velha.game.VelhaCanvas;

public class Menu extends List implements CommandListener {

	private final Command exitCommand = new Command("Sair", Command.EXIT, 0);
	private final VelhaMIDlet midlet;
	private String texto;

	public Menu(VelhaMIDlet midlet) {
		super("Jogo da Velha", List.IMPLICIT);

		this.midlet = midlet;

		try {
			append("Novo jogo", Image.createImage("/img/lapis.png"));
			append("Bluetooth", Image.createImage("/img/lapis.png"));
			append("Online", Image.createImage("/img/lapis.png"));
			append("Sobre", Image.createImage("/img/sobre.png"));
			append("Ajuda", Image.createImage("/img/ajuda.png"));

			texto = readAjuda();
		} catch (IOException ex) {
		}

		addCommand(exitCommand);
		setCommandListener(this);
	}

	private String readAjuda() throws IOException {
		InputStream in = getClass().getResourceAsStream("/velha/ajuda.txt");

		StringBuffer ajuda = new StringBuffer();
		int len;
		byte[] buf = new byte[1024];
		while ((len = in.read(buf)) != -1) {
			ajuda.append(new String(buf, 0, len, "UTF-8"));
		}
		return ajuda.toString();
	}

	public void commandAction(Command c, Displayable d) {
		if (c == exitCommand) {
			midlet.destroyApp(true);
		} else if (c == SELECT_COMMAND) {
			switch (getSelectedIndex()) {
			case 0:
				startVelha();
				break;
			case 1:
				midlet.getDisplay().setCurrent(new BTMenu(midlet));
				break;
			case 2:
				midlet.getDisplay().setCurrent(new NETMenu(midlet));
				break;
			case 3:
				Alert alert = new Alert("Sobre", "Jogo da Velha. v."
						+ midlet.getAppProperty("MIDlet-Version")
						+ "\nAntonio Diego\nhttp://antoniodiego.wapka.mobi",
						null, AlertType.INFO);
				alert.setTimeout(Alert.FOREVER);
				midlet.getDisplay().setCurrent(alert);
				break;
			case 4:
				Alert ajuda = new Alert("Ajuda", texto, null, AlertType.INFO);
				ajuda.setTimeout(Alert.FOREVER);
				midlet.getDisplay().setCurrent(ajuda);
				break;
			}
		}
	}
	
	private void startVelha(){
		Player p =  new Player();
		
		Rival r = new Rival();
		r.pontos = 0;
		r.caracter = Constantes.CARACTER_PLAYER_2;
		
		midlet.getDisplay().setCurrent(new VelhaCanvas(midlet, new Player(), r));
		
	}
}
